<template>
  <el-dialog
    v-model="dialogVisible"
    title="选择地点位置"
    width="800px" 
    align-center
    :before-close="handleCancel"
    top="6vh"
    class="location-select-dialog"
  >
    <div class="location-select-container">
      <!-- 搜索栏和操作按钮分组 -->
      <div class="search-bar-group">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索地点位置..."
          prefix-icon="el-icon-search"
          clearable
          @input="handleSearch"
          size="default"
          class="search-input"
        />
      </div>
      <!-- 当前选择显示 -->
      <div v-if="selectedLocation" class="selected-info-card">
        <span class="selected-label">当前选择：</span>
        <el-tag type="primary" size="default" closable @close="clearSelection">
          <span class="selected-path">{{ getLocationPath(selectedLocation) }}</span>
        </el-tag>
      </div>
      <!-- 树形控件 -->
      <div v-loading="loading" element-loading-text="正在加载地点位置数据..." style="display: flex;justify-content: space-between;">
        <div style="padding: 0; width: 30%; max-height: 340px; overflow-y: auto;margin-right: 10px;">
          <el-tree
            v-if="filteredLocationTree.length > 0"
            ref="treeRef"
            :data="filteredLocationTree"
            :props="{ children: 'children', label: 'name' }"
            node-key="id"
            :show-checkbox="false"
            :default-expand-all="false"
            :expand-on-click-node="false"
            @node-click="handleNodeClick"
            :highlight-current="true"
            class="location-tree simple-tree"
          >
            <template #default="{ node, data }">
              <div class="tree-node" :class="{ 'selected': selectedLocation?.id === data.id }">
                <span class="node-icon">
                  <i v-if="data.type === 'building'" class="el-icon-office-building" style="color: #409eff;"></i>
                  <i v-else-if="data.type === 'floor'" class="el-icon-menu" style="color: #67c23a;"></i>
                  <i v-else-if="data.type === 'room'" class="el-icon-house" style="color: #e6a23c;"></i>
                </span>
                <span class="node-label">{{ data.name }}</span>
                <span class="node-type">[{{ getTypeLabel(data.type) }}]</span>              
              </div>
            </template>
          </el-tree>
          <!-- 无数据时的空状态显示 -->
          <div v-else-if="!loading && currentTenantId" class="empty-state">
            <div class="empty-icon">
              <el-icon size="56" style="color: #409eff;"><OfficeBuilding /></el-icon>
            </div>
            <div class="empty-title">暂无地点位置数据</div>
            <div class="empty-description">
              当前商户下还没有创建任何地点位置，请先在地点位置管理中创建
            </div>
          </div>
          <!-- 商户ID缺失时的提示 -->
          <div v-else-if="!loading && !currentTenantId" class="no-tenant-state">
            <div class="empty-icon">
              <el-icon size="56" style="color: #e17055;"><QuestionFilled /></el-icon>
            </div>
            <div class="empty-title">缺少商户信息</div>
            <div class="empty-description">
              无法加载地点位置数据，请确保已正确设置商户ID
            </div>
          </div>
        </div>
        <div style="padding: 0; width: 70%; max-height: 340px; overflow-y: auto;">
            <el-table :data="equipList" @selection-change="handleSelectionChange" border>
              <el-table-column type="selection" width="40" />
              <el-table-column label="设备名称" prop="equipName" />
              <el-table-column label="设备编号" prop="equipNum" min-width="160" />
            </el-table>
          </div>
      </div>
    </div>
    <!-- 底部按钮 -->
    <template #footer>
      <div class="dialog-footer">
        <el-button size="large" @click="handleCancel">取消</el-button>
        <el-button 
          type="primary" 
          size="large" 
          @click="handleConfirm"
          :disabled="!selectedEquipFlag"
        >
          确定选择
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed, defineExpose } from 'vue'
import { ElMessage } from 'element-plus'
import {
  OfficeBuilding,
  QuestionFilled
} from '@element-plus/icons-vue'
import { getLocationTree, addEquipUsage } from '@/api/settle'
import { getEquipListByTenantId } from '@/api/collect'
import { 
  LocationTreeNode, 
  LocationType,
  LocationTypeLabels 
} from '@/api/types/location'
import type { MrsEquipUsageAddRequest } from '@/api/types/equipUsage'

// 组件属性
const emit = defineEmits(['confirm'])

// 响应式数据
const dialogVisible = ref(false)
const treeRef = ref()
const searchKeyword = ref('')
const loading = ref(false)
const currentTenantId = ref<number | undefined>()
const currentEnterpriseId = ref<number | undefined>()
const currentGroupId = ref<number | undefined>()
const selectedLocation = ref<LocationTreeNode | null>(null)
// 地点位置数据
const fullLocationTree = ref<LocationTreeNode[]>([])
// 设备类型，1-电表，2-水表，3-气表，4-智慧用电监控终端
const equip_type_eletric = 1
const equipType = ref(1)
const equipList = ref([])
const selectEquipList = ref<any[]>([]);

// 加载API数据
const loadLocationData = async () => {
  try {
    loading.value = true
    
    if (!currentTenantId.value) {
      ElMessage.error('缺少商户信息，无法加载地点位置数据')
      fullLocationTree.value = []
      return
    }
    
    const res = await getLocationTree(currentTenantId.value)
    
    if (res.success && res.data) {
      fullLocationTree.value = res.data
    } else {
      const errorMsg = res.msg || res.message || '加载地点位置数据失败'
      ElMessage.error(`加载失败: ${errorMsg}`)
      fullLocationTree.value = []
    }
  } catch (error) {
    ElMessage.error('网络请求失败，请检查网络连接后重试')
    fullLocationTree.value = []
  } finally {
    loading.value = false
  }
}

// 计算属性
// 过滤后的树数据（支持搜索）
const filteredLocationTree = computed(() => {
  let result = fullLocationTree.value
  
  // 如果有搜索关键词，进行搜索过滤
  if (searchKeyword.value.trim()) {
    result = searchFilterTree(result)
  }
  
  return result
})
const selectedEquipFlag = computed(() => {
  return selectEquipList.value && selectEquipList.value.length > 0
})

// 搜索过滤函数
const searchFilterTree = (nodes: LocationTreeNode[]): LocationTreeNode[] => {
  return nodes
    .map(node => {
      const filteredNode = { ...node }
      
      if (node.children) {
        const filteredChildren = searchFilterTree(node.children)
        if (filteredChildren.length > 0) {
          filteredNode.children = filteredChildren
        } else {
          delete filteredNode.children
        }
      }
      
      return filteredNode
    })
    .filter(node => {
      // 检查当前节点是否匹配搜索关键词
      const matchesSearch = node.name.toLowerCase().includes(searchKeyword.value.toLowerCase())
      
      // 检查子节点是否有匹配的
      const hasMatchingChildren = node.children && node.children.length > 0
      
      return matchesSearch || hasMatchingChildren
    })
}

// 获取类型标签
const getTypeLabel = (type: string) => {
  return LocationTypeLabels[type as LocationType] || '未知'
}

// 获取位置路径
const getLocationPath = (location: LocationTreeNode): string => {
  const path: string[] = []
  
  // 递归查找路径
  const findPath = (nodes: LocationTreeNode[], targetId: string | number, currentPath: string[] = []): boolean => {
    for (const node of nodes) {
      const newPath = [...currentPath, node.name]
      
      if (node.id === targetId) {
        path.push(...newPath)
        return true
      }
      
      if (node.children && findPath(node.children, targetId, newPath)) {
        return true
      }
    }
    return false
  }
  
  findPath(fullLocationTree.value, location.id)
  return path.join(' -> ') || location.name
}

const getEquipList = (locationId: any) => {
  const requestData = {
    tenantId: currentTenantId.value,
    equipType: equipType.value,
    locationId: locationId
  }  
  getEquipListByTenantId(requestData).then((res: any) => {
    equipList.value = res.data
  })
  .catch((err: any) => {
    console.error('err', err.msg)
  })
}

// 处理搜索
const handleSearch = () => {
  // 搜索功能已通过计算属性实现
}

// 处理节点点击
const handleNodeClick = (location: LocationTreeNode) => {
  selectedLocation.value = location
  getEquipList(location.id)
}

// 清除选择
const clearSelection = () => {
  selectedLocation.value = null
  getEquipList(null)
}

// 处理批量选择变化
const handleSelectionChange = (val: any[]) => {
  selectEquipList.value = val;
};

// 处理确认
const handleConfirm = async () => {
  if (!selectEquipList.value || selectEquipList.value.length == 0) {
    ElMessage.warning(equipType.value == equip_type_eletric ? '请先选择电表' : '请先选择水表')
    return
  }
  
  await saveEquipUsage(function (successCount: number) {
    if (successCount == selectEquipList.value.length) {
      emit('confirm')
      dialogVisible.value = false
    }
  })

}

const saveEquipUsage = async (callback: Function) => {
  let successCount = 0, closeCount = 0
  selectEquipList.value.map((item) => {
    const equipUsageData: MrsEquipUsageAddRequest = {
      equipType: item.equipType,
      equipName: item.equipName,
      equipNum: item.equipNum,
      groupId: currentGroupId.value,
      enterpriseId: currentEnterpriseId.value,
      locationId: item.locationId,
    }
    addEquipUsage(equipUsageData).then((res: any) => {
      if (res.success) {
        successCount++
      }
      closeCount++
      if (closeCount == selectEquipList.value.length) {
        callback(successCount)
      }
    })
    .catch((err: any) => {
      ElMessage.error(err.msg)
    })
  });
}

// 处理取消
const handleCancel = () => {
  dialogVisible.value = false
  selectedLocation.value = null
  searchKeyword.value = ''
}

// 打开对话框
const openDialog = async (tenantId: number, type: number, groupId: number, enterpriseId: number) => {
  dialogVisible.value = true
  selectedLocation.value = null
  searchKeyword.value = ''
  equipType.value = type
  currentGroupId.value = groupId
  currentEnterpriseId.value = enterpriseId
  
  // 设置当前商户ID
  if (tenantId) {
    currentTenantId.value = tenantId
  } else {
    currentTenantId.value = undefined
  }
  
  try {
    // 加载数据
    await loadLocationData()
    getEquipList(null)
  } catch (error) {
    ElMessage.error('初始化失败，请重试')
  }
}

// 暴露方法
defineExpose({
  openDialog
})
</script>

<style scoped>
.location-select-container {
  max-height: 500px;
  padding: 0 8px 8px 8px;
}
.search-bar-group {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 10px;
}
.add-root-btn {
  border-radius: 16px;
  min-width: 90px;
  font-size: 14px;
  padding: 0 16px;
  height: 32px;
  box-shadow: none;
}
.selected-info-card {
  display: flex;
  align-items: center;
  gap: 8px;
  background: #f6faff;
  border: 1px solid #e3eaf3;
  border-radius: 8px;
  padding: 6px 14px;
  margin-bottom: 8px;
  font-size: 14px;
}
.selected-label {
  color: #409eff;
  font-weight: 500;
}
.selected-path {
  font-weight: 500;
}
.location-tree.simple-tree {
  max-height: 340px;
  overflow-y: auto;
  border: 1px solid #e3eaf3;
  border-radius: 6px;
  padding: 6px 4px;
  background: #fcfdff;
}
.tree-node {
  display: flex;
  align-items: center;
  width: 100%;
  padding: 4px 0;
  border-radius: 4px;
  transition: background 0.15s;
  font-size: 15px;
}
.tree-node:hover {
  background-color: #f3f8fd;
}
.tree-node.selected {
  background-color: #eaf6ff;
  border: 1px solid #409eff44;
}
.node-icon {
  margin-right: 8px;
  color: #409eff;
  font-size: 18px;
}
.node-label {
  font-weight: 500;
  flex: 1;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.node-type {
  margin-left: 8px;
  font-size: 12px;
  color: #b0b4bb;
}
.simple-actions {
  display: flex;
  gap: 2px;
  opacity: 0;
  transition: opacity 0.18s;
  margin-left: auto;
}
.tree-node:hover .simple-actions {
  opacity: 1;
}
.simple-actions .el-button {
  border-radius: 50%;
  padding: 0;
  min-width: 24px;
  height: 24px;
  font-size: 13px;
  box-shadow: none;
}
.simple-actions .el-button--info {
  background: #eaf1fa;
  color: #409eff;
  border: none;
}
.simple-actions .el-button--info:hover {
  background: #409eff;
  color: #fff;
}
.empty-state,
.no-tenant-state {
  text-align: center;
  padding: 40px 12px;
  border-radius: 10px;
  border: 1px solid #e4e7ed;
  background: #f8fafc;
  margin-top: 18px;
}
.empty-icon {
  margin-bottom: 16px;
}
.empty-title {
  font-size: 17px;
  color: #303133;
  margin-bottom: 8px;
  font-weight: 600;
}
.empty-description {
  font-size: 13px;
  color: #606266;
  line-height: 1.6;
}
.dialog-footer {
  text-align: center;
}
</style>